<?php
include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";
\ns_core\m_load::load("ns_model.message.message_explain");
\ns_core\m_load::load("ns_core.m_config");
class message extends \ns_model\message\message_explain
{
    public $arr_objects = '';

    public $source_id = '';
    public $msg_id = '';
    public $arr_cp_config = array();
    //异步反馈参数
    public $content_id = '';
    public $node_id = '';
    public $domain = '';

    //动作映射
    private $action_map = array(
        'REGIST' => 1,
        'UPDATE' => 2,
        'DELETE' => 3,
    );

    /**
     * 数据类型和数字映射
     * @var array
     */
    private $type_map = array(
        'Series'            => 4,
        'Program'           => 5,
        'Movie'             => 6,
        'Picture'           => 7,
        'Category'          => 8,
        'Channel'           => 9,
        'PhysicalChannel'   => 10,
        'Schedule'          => 11
    );

    public function explain($message)
    {
        $this->source_id = $message['nns_cp_id'];
        $this->msg_id = $message['nns_message_id'];
        //获取CP配置
        $cp_info = \m_config::_get_cp_info($this->source_id);
        $this->arr_cp_config = $cp_info['data_info']['nns_config'];
        \ns_core\m_load::load_np("np_xml2array.class.php");
        //获取本地数据
        $content = $this->get_message_content($message);
        if($content['ret'] != 0 || strlen($content['data_info']) < 1)
        {
            \m_config::write_message_execute_log("消息接收成功,注入失败，消息ID[{$message['nns_message_id']}]",$this->source_id);
            $this->create_xml_respond_msg_to_csp(NS_CDS_FAIL, "消息接收成功,注入失败，消息ID[{$message['nns_message_id']}]" . $content['reason']);
            return $content;
        }
        $str_content = \m_config::trim_xml_header($content['data_info']);
        if(!\m_config::is_xml($str_content))
        {
            \m_config::write_message_execute_log("消息接收成功,注入失败,消息ID[{$message['nns_message_id']}]xml内容非xml结构",$this->source_id);
            $this->create_xml_respond_msg_to_csp(NS_CDS_FAIL, "消息接收成功,注入失败,消息ID[{$message['nns_message_id']}]xml内容非xml结构");
            return \m_config::return_data(NS_CDS_FAIL,"消息ID[{$message['nns_message_id']}]xml内容非xml结构");
        }
//        $str_content = file_get_contents('test.xml');
        //解析下载的XML
        $dom = new DOMDocument('1.0', 'utf-8');
        $dom->loadXML($str_content);
        $xml = $dom->saveXML();
        $xml_arr = np_xml2array::getArrayData($xml);
        if ($xml_arr["ret"] == 0)
        {
            \m_config::write_message_execute_log("工单XML解析失败",$this->source_id);
            $this->create_xml_respond_msg_to_csp(NS_CDS_FAIL, "工单XML解析失败");
            return \m_config::return_data(NS_CDS_FAIL,"消息ID[{$message['nns_message_id']}]工单XML解析失败");
        }

        $this->arr_objects = null;
        //获取objects节点下object内容
        foreach ($xml_arr['data']['children'] as $val)
        {
            if (empty($this->arr_objects) && $val['name'] == 'Objects')
            {
                $this->arr_objects = $val['children'];
            }
        }
        unset($xml_arr);
        $obj_first = true;

        // 循环Object列表，将不同类型数据放到不同的数组中
        if (!empty($this->arr_objects) && is_array($this->arr_objects))
        {
            foreach ($this->arr_objects as $key => $obj)
            {
                $tmp_type = $obj['attributes']['ElementType'];
                $element_types[] = $tmp_type;
                if(isset($obj['children']) && is_array($obj['children']) && !empty($obj['children']))
                {
                    foreach ($obj['children'] as $v)
                    {
                        $movie_info[$v['attributes']['Name']] = isset($v['content']) ? $v['content'] : '';
                    }
                }

                $this->content_id = $obj['attributes']['PhysicalContentID'];
                $this->domain = isset($movie_info['Domain']) && !empty($movie_info['Domain']) ? $movie_info['Domain'] : '';
                $this->node_id = isset($movie_info['dstPop']) && !empty($movie_info['dstPop']) ? $movie_info['dstPop'] : '';

                switch ($obj['attributes']['Action'])
                {
                    case 'REGIST':
                        if(empty($movie_info['FileURL']))
                        {
                            \m_config::write_message_execute_log('XML文件地址为空',$this->source_id);
                            $this->create_xml_respond_msg_to_csp(NS_CDS_FAIL, "XML文件地址为空");
                            return array(NS_CDS_FAIL,'XML文件地址为空');
                        }
                        //截取文件后缀
                        $file_1 = explode("?",$movie_info['FileURL']);
                        $file_2 = explode('.',$file_1[0]);
                        if(count($file_2) > 1)
                        {
                            $file_type = end($file_2);
                        }
                        else
                        {
                            $file_type = "m3u8";
                        }

                        //文件大小
                        $file_size = !empty($movie_info['FileSize']) ? ceil($movie_info['FileSize']/1024) : '1';
                        //时长
                        if(!empty($movie_info['Duration']))
                        {
                            $time_len = substr($movie_info['Duration'],0,2).":".substr($movie_info['Duration'],2,2).":".substr($movie_info['Duration'],4,2);
                            $duration = strtotime($time_len)-strtotime(date('Y-m-d'));
                        }
                        else
                        {
                            $duration = 0;
                        }

                        //虚拟构建主媒资
                        $arr_series_info = array(
                            'clipname' => !empty($movie_info['CPContentID']) ? $movie_info['CPContentID'].'-'.$obj['attributes']['PhysicalContentID'] : $obj['attributes']['PhysicalContentID'],
                            'year' => date('Y'),
                            'relasetime' => date('Y-m-d'),
                            'serialcount' => 1,
                            'duration' => $duration,
                            'originalid' => $obj['attributes']['PhysicalContentID'],
                            'contentProvider' => !empty($movie_info['CPContentID']) ? $movie_info['CPContentID'] : $this->source_id,

                        );
                        $result = $this->video_regist_execute($arr_series_info);
                        if($result['ret'] != NS_CDS_FAIL)
                        {
                            //虚拟构建分集
                            $arr_index_info = array(
                                'partname' => !empty($movie_info['CPContentID']) ? $movie_info['CPContentID'].'-'.$obj['attributes']['PhysicalContentID'] : $obj['attributes']['PhysicalContentID'],
                                'duration' => $duration,
                                'oriassetid' => $obj['attributes']['PhysicalContentID'],
                                'originalid' => $obj['attributes']['PhysicalContentID'],
                                'relasetime' => date('Y-m-d'),
                                'clip' => 0,
                            );
                            $result = $this->index_execute($arr_index_info);
                            if($result['ret'] != NS_CDS_FAIL)
                            {
                                $arr_media_info = array(
                                    'video_import_id' => $obj['attributes']['PhysicalContentID'],
                                    'index_import_id' => $obj['attributes']['PhysicalContentID'],
                                    'media_import_id' => $obj['attributes']['PhysicalContentID'],
                                    'file_path' => $movie_info['FileURL'],
                                    'file_definition' => 'hd',//默认高清
                                    'file_bit_rate' => !empty($movie_info['BitRateType']) ? $movie_info['BitRateType'] : '',
                                    'file_type' => $file_type,
                                    'file_size' => $file_size,
                                    'file_time_len' => $duration,
                                    'domain' => $movie_info['Domain'],
                                );
                                $result = $this->media_execute($arr_media_info);
                            }
                        }
                        break;
                    case 'DELETE':
                        //删除虚构
                        $arr_series_info = array(
                            'originalid' => $obj['attributes']['PhysicalContentID'],
                        );
                        $result = $this->video_del_execute($arr_series_info);
                }
                // 修改消息的媒资类型和操作类型
                if ($obj_first)
                {
                    $message_data['nns_action'] = $this->action_map[$obj['attributes']['Action']];
                    $message_data['nns_type'] = $this->type_map[$tmp_type];
                    $this->update_message_table($this->msg_id, $message_data);
                    $obj_first = false;
                }
            }
        }
        if($result['ret'] != NS_CDS_SUCCE)
        {
            $this->create_xml_respond_msg_to_csp($result['ret'],$result['reason']);
        }
        return $result;

    }
    /**
     * 主媒资队列注入
     * @param $data
     * @return array|void
     *
     */
    private function video_regist_execute($content)
    {
        //获取view_type
        $view_type = '0';
        $asset_category = '电影';
        $do_category = array(
            'base_info' => array(
                'nns_name' => $asset_category,   //栏目名称支持多层目录，多层目录的时候 /分割
                'nns_import_category_id' => '', //栏目名称支持多层目录，多层目录的时候 /分割
                'nns_cp_id' => $this->source_id,
                'nns_import_parent_category_id' => '',
                'nns_video_type' => '0',  //媒资类型  0 点播 | 1 直播
            ),
        );
        //创建栏目
        $result = $this->category_action('add', $do_category);
        if($result['ret'] != 0)
        {
            return $result;
        }
        if(!isset($result['data_info']['base_info']['nns_id']) || strlen($result['data_info']['base_info']['nns_id']) <1)
        {
            return m_config::return_data(1,'创建栏目失败');
        }
        $nns_category_id = $result['data_info']['base_info']['nns_id'];

        //导演信息
        $director='';
        $directornew='';
        //演员信息
        $leader='';
        $leadernew='';
        $adaptor='';
        $adaptornew='';
        $add_series = array(
            'base_info' => array(
                'nns_name' => $content['clipname'],
                'nns_view_type' => $view_type,
                'nns_org_type' => '0',
                'nns_tag' => '26,',
                'nns_director' => $director,
                'nns_actor' => $leader,
                'nns_show_time' => $content['relasetime'],
                'nns_view_len' => $content['duration'],
                'nns_all_index' => intval($content['serialcount']),
                'nns_new_index' => 0,
                'nns_area' => '',
                'nns_image0' => '',
                'nns_image1' => '',
                'nns_image2' => '',
                'nns_image3' => '',
                'nns_image4' => '',
                'nns_image5' => '',
                'nns_summary' => '',
                'nns_remark' => '',
                'nns_category_id' => $nns_category_id,
                'nns_play_count' => '0',
                'nns_score_total' => 0,//评分
                'nns_score_count' => '0',
                'nns_point' => '0',
                'nns_copyright_date' => $content['year'],
                'nns_asset_import_id' => $content['originalid'],
                'nns_pinyin' => '',
                'nns_pinyin_length' => 0,
                'nns_alias_name' => '',
                'nns_eng_name' => '',
                'nns_language' => '',
                'nns_text_lang' => '',
                'nns_producer' => isset($content['contentProvider']) ? $content['contentProvider'] : '',
                'nns_screenwriter' => $adaptor,
                'nns_play_role' => '',
                'nns_copyright_range' => '',
                'nns_vod_part' => '',
                'nns_keyword' => '',
                'nns_import_source' => $this->source_id,
                'nns_kind' => '',
                'nns_copyright' => '',
                'nns_clarity' => '',
                'nns_image_v' => '',
                'nns_image_s' => '',
                'nns_image_h' => '',
                'nns_cp_id' => $this->source_id,
                'nns_conf_info' => '',
                'nns_ext_url' => '',
                'nns_ishuaxu' => isset($content['ishuaxu']) ? (int)$content['ishuaxu'] : 0,
                'nns_positiveoriginalid' => isset($content['positiveoriginalid']) ? $content['positiveoriginalid'] : '',
            ), //基本信息（存储于nns_vod表中）
            'ex_info' => array(
                'svc_item_id' => '',
                'month_clicks' => '',
                'week_clicks' => '',
                'base_id' => '',
                'asset_path' => '',
                'ex_tag' => '',
                'full_spell' => '',
                'awards' => '',
                'year' => $content['year'],
                'play_time' => '',
                'channel' => '',
                'first_spell' => '',
                'directornew' => $directornew,
                'playernew' => $leadernew,
                'adaptornew' => $adaptornew,
                'third_asset_id' => '',
            ), //扩展信息（存储于nns_vod_ex表中）
        );
        $result = $this->vod_action('add', $add_series);
        return $result;
    }
    /**
     * 主媒资删除
     */
    public function video_del_execute($content)
    {
        $delete_params = array(
            'base_info' => array(
                'nns_cp_id' => $this->source_id,
                'nns_asset_import_id' => $content['originalid'],
                'nns_import_source' => $this->source_id,
            ),
        );
        $result = $this->vod_action('delete', $delete_params);
        return $result;
    }

    /**
     * 分集队列注入
     * @param $data
     * @return array|multitype
     */
    private function index_execute($content)
    {
        //导演信息
        $director='';
        $directornew='';
        //演员信息
        $leader='';
        $leadernew='';
        $adaptornew='';
        $add_index = array(
            'base_info' => array(
                'nns_name' => $content['partname'],
                'nns_index' => $content['clip'],
                'nns_time_len' => $content['duration'],
                'nns_summary' => '',
                'nns_image' =>  '',
                'nns_play_count' => 0,
                'nns_score_total' => 0,
                'nns_score_count' => 0,
                'nns_video_import_id' => $content['oriassetid'],
                'nns_import_id' => $content['originalid'],
                'nns_import_source' => $this->source_id,
                'nns_director' => $director,
                'nns_actor' => $leader,
                'nns_release_time' => $content['relasetime'],
                'nns_update_time' => $content['relasetime'],
                'nns_watch_focus' => '',
                'nns_cp_id' => $this->source_id,
                'nns_conf_info' => '',
                'nns_ext_url' => '',
            ),
            'ex_info' => array(
                'isintact' => 0,
                'subordinate_name' => '',
                'initials' => '',
                'publisher' => '',
                'first_spell' => '',
                'caption_language' => '',
                'language' => '',
                'region' => '',
                'adaptor' => '',
                'sreach_key' => '',
                'event_tag' => '',
                'year' => '',
                'sort_name' => '',
                'directornew' => $directornew,
                'playernew' => $leadernew,
                'adaptornew' => $adaptornew,
                'third_clip_id' => '',
            ),
        );

        //分集注入
        $re = $this->index_action('add', $add_index);
        return $re;
    }

    /**
     * 片源队列注入
     * @param $data
     * @return array|multitype
     */
    private function media_execute($content)
    {
        $add_media = array(
            'base_info' => array(
                'nns_name' => '',
                'nns_type' => 1,
                'nns_url' => $content['file_path'],
                'nns_tag' => '26,',
                'nns_mode' => $content['file_definition'],
                'nns_kbps' => $content['file_bit_rate'],
                'nns_content_id ' => '',
                'nns_content_state' => 0,
                'nns_filetype' => $content['file_type'],
                'nns_play_count' => '0',
                'nns_score_total' => '0',
                'nns_score_count' => '0',
                'nns_video_import_id' => $content['video_import_id'],
                'nns_index_import_id' => $content['index_import_id'],
                'nns_import_id' => $content['media_import_id'],
                'nns_import_source' => $this->source_id,
                'nns_dimensions' => '0',
                'nns_ext_url' => '',
                'nns_file_size' => $content['file_size'],
                'nns_file_time_len' => $content['file_time_len'],
                'nns_file_frame_rate' => '',
                'nns_file_resolution' => '',
                'nns_cp_id' => $this->source_id,
                'nns_ext_info' => '',
                'nns_drm_enabled' => 0,
                'nns_drm_encrypt_solution' => '',
                'nns_drm_ext_info' => '',
                'nns_domain' => $content['domain'],
                'nns_media_type' => 1,
                'nns_original_live_id' => '',
                'nns_start_time' => '',
                'nns_media_service' => '',
                'nns_conf_info' => '',
                'nns_encode_flag' => 0,
                'nns_live_to_media' => '',
                'nns_media_service_type' => '',
                'nns_content_id' => '',
            ),
            'ex_info' => array(
                'file_hash' => '',
                'file_width' => '',
                'file_height' => '',
                'file_scale' => '',
                'file_coding' => '',
                'third_file_id' => '',
            )
        );
        $re = $this->media_action('add', $add_media);
        return $re;
    }
    /**
     * 更新nns_mgtvbk_message表记录状态
     * @param string $id 数据库表nns_mgtvbk_message记录主键id
     * @param array $update_fields 需要更新的字段和值,例如:array('nns_message_state' => 3)
     */
    public function update_message_table($id, $update_fields)
    {
        //需要更新的字段不为空的时候它的类型必须是个数组
        if (empty($id) || (count($update_fields) > 0 && !is_array($update_fields)))
        {
            return;
        }
        $sql = 'update nns_mgtvbk_message set ';
        foreach ($update_fields as $field => $value)
        {
            $sql .= "$field='$value',";
        }
        $sql = rtrim($sql, ',');
        $sql .= " where nns_message_id='{$id}'";
        nl_execute_by_db($sql, \m_config::get_dc()->db());
    }
    /**
      * @param $arr_data //封装好了的反馈信息 array(
    *                                          'cdn_id' => ,注入cdn的id
    *                                          'site_id' => ,配置的站点id
    *                                          'mg_asset_type' => ,注入媒资类型
    *                                          'mg_asset_id' => ,主媒资的消息注入id
    *                                          'mg_part_id' => ,分集的消息注入id
    *                                          'mg_file_id' => ,);片源的消息注入id,
    */
    public function is_ok($message_id, $code, $reason, $arr_data, $sp_id)
    {
        if(empty($message_id))
        {
            \m_config::write_callback_log("片源注入异步反馈上游：消息ID为空，不反馈上游",$this->source_id,'nomessageid');
            return;
        }
        $this->msg_id = $message_id;
        if($arr_data['mg_asset_type'] != 3)
        {
            return ;
        }
        //获取来源ID
        $source_path = m_config::return_child_path(dirname(__FILE__));
        $source_arr = explode("/",$source_path);
        $this->source_id = end($source_arr);
        \m_config::write_callback_log("片源注入异步反馈上游参数：".var_export($arr_data,true),$this->source_id,$this->msg_id);
        //获取CP配置
        $cp_info = \m_config::_get_cp_info($this->source_id);
        $this->arr_cp_config = $cp_info['data_info']['nns_config'];
        //获取片源信息，使用import_id查询nodeid与domain
        $this->content_id = $arr_data["mg_file_id"];
        $vod_media_re = \nl_vod_media_v2::query_vod_media_info_by_import_id(\m_config::get_dc(),$this->content_id,$this->source_id);
        \m_config::write_callback_log("片源注入异步反馈上游：片源查询结果：".var_export($vod_media_re,true),$this->source_id,$this->msg_id);
        if($vod_media_re['ret'] == 0)
        {
            if(count($vod_media_re['data_info']) <= 1) //有且仅有一个片源
            {
                $this->domain = $vod_media_re['data_info'][0]['nns_domain'];
                if(strlen($vod_media_re['data_info'][0]['nns_ext_info']) > 0)
                {
                    $ext_info = json_decode($vod_media_re['data_info'][0]['nns_ext_info'],true);
                    $this->node_id = isset($ext_info['node_id']) ? $ext_info['node_id'] : '';
                }
            }
            else
            {
                foreach ($vod_media_re['data_info'] as $vod_media) //有多个注入ID相同，状态不同的片源
                {
                    if($vod_media['nns_deleted'] != 1)//只获取未删除的片源参数
                    {
                        $this->domain = $vod_media['nns_domain'];
                        if(strlen($vod_media['nns_ext_info']) > 0)
                        {
                            $ext_info = json_decode($vod_media['nns_ext_info'],true);
                            $this->node_id = isset($ext_info['node_id']) ? $ext_info['node_id'] : '';
                        }
                        break;
                    }

                }
            }
        }
        unset($vod_media_re);
        $this->create_xml_respond_msg_to_csp($code,$reason);
    }

    /**
     * 异步上游反馈
     * @param $ret
     * @param $reason
     */
    private function create_xml_respond_msg_to_csp($ret,$reason)
    {
        if($ret != 0)
        {
            $ret = -1;
        }
        $ResultFileURL = '';
        if(isset($this->arr_cp_config['site_id']) && !empty($this->arr_cp_config['site_id']))
        {
            $notify_arr = array(
                'NodeID' => $this->node_id,
                'Domain' => $this->domain,
                'ResultCode' => $ret
            );
            $xml_url = $this->build_result($this->content_id,$reason,$notify_arr);
            if(!empty($xml_url))
            {
                $ResultFileURL = $this->arr_cp_config['site_id'] . "/" . $xml_url;
            }
        }

        $notify_msg = "[异步反馈地址]：".$this->arr_cp_config["site_callback_url"]."[异步反馈消息]:{$this->msg_id}[状态/结果]:{$ret}/{$reason}"."[其他参数]:".$ResultFileURL;
        \m_config::write_callback_log($notify_msg,$this->source_id,$this->msg_id);
        if(empty($this->arr_cp_config["site_callback_url"]))
        {
            return ;
        }
        $soap = new SoapClient($this->arr_cp_config["site_callback_url"], array('trace'=>true));
        $soap_re = $soap->ContentPreloadResult($this->source_id,$this->msg_id,$ret,$reason,$ResultFileURL);
        \m_config::write_callback_log("[异步反馈结果]：".var_export($soap_re,true),$this->source_id,$this->msg_id);
    }

    /**
     * 异步反馈XML工单拼装
     * @param $contentid
     * @param $reason
     * @param $info
     * @return string|void
     */
    private function build_result($contentid,$reason,$info)
    {
        $dom = new DOMDocument('1.0', 'utf-8');
        $msg = $dom->createElement('ADI');
        $dom->appendChild($msg);
        $response = $dom->createElement('Reply');
        $msg->appendChild($response);

        $result_info = $dom->createElement('Resultinfo');
        $response->appendChild($result_info);
        $result_info->setAttribute('ContentID', $contentid);

        $description = $dom->createElement('Description');
        $result_info->appendChild($description);
        $description->nodeValue = $reason;
        foreach ($info as $key=>$value)
        {
            $property = $dom->createElement('Property');
            $result_info->appendChild($property);
            $property->setAttribute('Name', $key);
            $property->nodeValue = $value;
        }

        $notify_xml = $dom->saveXML();
        //读取毫秒级时间
        list ($usec, $sec) = explode(' ', microtime());
        $time = str_pad(intval(substr($usec, 2, 4)),4,'0',STR_PAD_LEFT);
        $three_rand = rand(100, 999);
        $file_name = $this->source_id . "_{$three_rand}_{$time}.xml";
        $file_path = date("Ymd")."/".date("H")."/{$file_name}";
        $notify_url = "/messaage_notify_xml/{$file_path}";
        $result_make_dir = \m_config::make_dir($notify_url);
        if($result_make_dir['ret'] != 0)
        {
            \m_config::write_callback_log("文件路径生产绝对路径失败，请检查目录权限{$notify_url}",$this->source_id,$this->msg_id);
            return '';
        }
        if(!isset($result_make_dir['data_info']['absolute_dir']) || strlen($result_make_dir['data_info']['absolute_dir']) <1)
        {
            \m_config::write_callback_log("文件路径生产绝对路径失败，请检查目录权限{$notify_url}",$this->source_id,$this->msg_id);
            return '';
        }
        @file_put_contents($result_make_dir['data_info']['absolute_dir'], $notify_xml);
        return $file_path;
    }
}
